local loader = require "atlas"

local atlas, cell, grid

local function createGrid(w, h)
    grid = love.graphics.newQuad(0, 0, w, h, 32, 32)
    cell = love.graphics.newCanvas(32, 32)
    cell:setWrap("repeat", "repeat")
    love.graphics.setCanvas(cell)
    love.graphics.setColor(255, 255, 255, 255)
    love.graphics.rectangle("fill", 0, 0, 16, 16)
    love.graphics.rectangle("fill", 16, 16, 16, 16)
    love.graphics.setColor(120, 120, 120, 255)
    love.graphics.rectangle("fill", 16, 0, 16, 16)
    love.graphics.rectangle("fill", 0, 16, 16, 16)
    love.graphics.setCanvas()
end

function love.load()
  -- DEBUG: ZeroBrane Studio Lua IDE debugging
  if arg[#arg] == "-debug" then require("mobdebug").start() end

    atlas = loader.Atlas(0, 0, false, "out", nil, true, false)
--  atlas = loader.AtlasCL()

--  atlas.build("out/")
--  atlas.out("aaa", "png")

    if atlas == "toolarge" then
        print("System limits exceeded!")
        love.event.quit()
    elseif atlas then
        local bak = atlas.map:newImageData()
        local w, h = atlas.map:getWidth(), atlas.map:getHeight()

        love.window.setMode(w, h)
        atlas.map = love.graphics.newCanvas(w, h)

        love.graphics.setCanvas(atlas.map)
        love.graphics.draw(love.graphics.newImage(bak))
        love.graphics.setCanvas()

        love.window.setTitle(love.window.getTitle() .. " (" .. w .. " x " .. h .. ", " .. #atlas.uv .. " images)")
        createGrid(w, h)
    end
end

function love.draw()
    love.graphics.draw(cell, grid)
    love.graphics.setColor(255, 255, 255, 255)
    if atlas then
        love.graphics.draw(atlas.map)
    end
end

function love.keypressed(key, isRepeat)
    if key == "escape" then
        love.event.quit()
    end
end
